/*
 Functions to manage message subjects in inbox and outbox
 */
function manageMailBoxMessages2(page){
	
	if (!page) {
		page = document;
	}
	
	var messageViewType = getMessageViewType();
	
	if (messageViewType > 2) {
		return;
	}	
	
	var tableBodyToProcess = $X(".//*[@id='deleteMessages']/table/tbody");	
	
	processMessageTable( tableBodyToProcess );
}

function processMessageTable ( tablebody )	{
	var messageTextDivs = $x("./tr[@class='text' or @class='entry' or @class='entry ' or @class='entry new']", tablebody);
	var x = 0;
    var c = 0;
    var regExpPatternForMarker = '';
    var localizedDateFormat = userSettingValues['LOCALIZED_DATEFORMAT'];
    
    c = messageMarkerSeparator.length;
    var messageMarkerSeparatorForRegex = '';
    for (x = 0; x != c; x++) {
    	messageMarkerSeparatorForRegex += '\\' + messageMarkerSeparator[x];
    }
    
    for ( key in defaultSubjectIcons )	{
    	regExpPatternForMarker += messageMarkerSeparatorForRegex + key + '|';
    }
    
    for ( key in userDefinedPicturePaths )	{
    	regExpPatternForMarker += messageMarkerSeparatorForRegex + key + '|';
    }
    
    var regExForMarker = new RegExp(regExpPatternForMarker.substring(0, regExpPatternForMarker.length - 1));
	if ( !userSettingValues['CASE_SENSITIVE_MARKER_CHECK'] )	{
		regExForMarker.ignoreCase = !userSettingValues['CASE_SENSITIVE_MARKER_CHECK'];
		regExForMarker.compile();		
	}
	
	var xPathForMessageTextDiv = './td/div';	
	var trShifter = 3;
	if ( getMessageViewType() == 2 )	{		
		xPathForMessageTextDiv = './td/div';
		trShifter = 2;
	}
    
    c = ( messageTextDivs.length / trShifter );
    var actualMarker = null;
    var markerMessage = '';

    for (x = 0; x != c; x++) {
		var currentMessageTr = messageTextDivs[trShifter*x + 1];
		var messageTextDiv = null;
		messageTextDiv = HTMLDivElement();
		messageTextDiv = $X(xPathForMessageTextDiv, currentMessageTr );		
		
		var messageSubjectTr = messageTextDivs[trShifter*x];		
		var messageSubjectTd = document.createElement('td');
		messageSubjectTd = $X("./td[@class='subject']", messageSubjectTr );		

		var fullMessage = messageTextDiv.innerHTML;
		/*
		if ( fullMessage.indexOf( ( messageMarkerSeparator + 'IMAGE=') ) > -1 )	{	
        	var imgLink = fullMessage.substring( fullMessage.indexOf( messageMarkerSeparator + 'IMAGE=') );
        	imgLink = imgLink.substring(messageMarkerSeparator.length+6, imgLink.indexOf(messageMarkerSeparator, messageMarkerSeparator.length));        	
        	var linkedImage = new Image();
        	linkedImage.setAttribute('src', 'http://'+imgLink);
        	linkedImage.setAttribute('width', '680px');
        	messageTextDiv.appendChild( linkedImage );
        }
		*/
		if ( localizedDateFormat )	{
			messageSubjectTr = formatDateCell(messageSubjectTr);		
		}
		actualMarker = null;
		actualMarker = regExForMarker.exec(fullMessage);
		
        if ( actualMarker != null ) {						
			markerMessage = fullMessage.substring( fullMessage.indexOf(actualMarker) );	
			markerMessage = markerMessage.substring(messageMarkerSeparator.length, markerMessage.indexOf(messageMarkerSeparator, messageMarkerSeparator.length));
			
			if ( markerMessage != 'undefined' && markerMessage != null && markerMessage != '' ){
				// Maybe not need to convert Uppercase()
				splittedText = markerMessage.split(' ');
				if ( myTrim(splittedText[0]) == getKeywordsInLang('CUSTOM') ||  myTrim(splittedText[0]) == CUSTOM_KEYWORD ||  myTrim(splittedText[0]) == HUN_CUSTOM_KEYWORD )	{
					var customKeyWordRegex = new RegExp( getKeywordsInLang('CUSTOM') );
					// Ide egy try-catch-finally, létre kell hozni a kiemelő str-nek és a képnek egy-egy változót, hiba esetén null bele és a finally ágban ha nem null akkor belerakjuk
					messageSubjectTd.innerHTML = appendMessageType2(messageSubjectTd.innerHTML, markerMessage.replace(customKeyWordRegex, '') );
					messageSubjectTd.appendChild(createSubjectPicture(defaultSubjectIcons[myTrim(splittedText[0])]));
					continue;
				}
				messageSubjectTd.innerHTML = appendMessageType2(messageSubjectTd.innerHTML, myTrim(splittedText[0]));
				switch (splittedText.length) {
					case 3: // EXCHANGE SPECIFIED WITH RESOURCES					
						var iconPath = resourceNamesForAdditionalParams[myTrim(splittedText[1])];					
						messageSubjectTd.appendChild(createSubjectPicture( iconPath ));						
						messageSubjectTd.appendChild(createSubjectPicture(EXCHANGE_DIRECTION_ICON_PATH));
						iconPath = resourceNamesForAdditionalParams[myTrim(splittedText[2])];
						messageSubjectTd.appendChild(createSubjectPicture( iconPath ));		
						break;
					case 2: // BUY / SELL SPECIFIED WITH RESOURCES 
						var iconPath = resourceNamesForAdditionalParams[myTrim(splittedText[1])];
						messageSubjectTd.appendChild(createSubjectPicture( iconPath ));
						break;						
					case 1:	// ALL OTHER
						var pictureLink = getPictureSrc(myTrim(splittedText[0]));
						if ( pictureLink == null )	{
							messageSubjectTd.innerHTML = messageSubjectTd.innerHTML.replace(myTrim(splittedText[0]),  getOtherTextInLang( 'OLD_VERSION' )  );
						}
						else	{
							messageSubjectTd.appendChild(createSubjectPicture( pictureLink ));
						}
						break;
					default: 
						messageSubjectTd.innerHTML += getOtherTextInLang( 'ERROR_IN_KEYWORD' );
				}
			}
        }
        else {
        	var circularMessage = messageSubjectTd.innerHTML.indexOf('-') > 1;
        	if (userSettingValues['CHECK_ALLY_MESSAGES_WITHOUT_MARKER'] && circularMessage && 1 == getMessageViewType() ) {
        		var tick = $X("./td/input[starts-with(@name,'delete')]", messageSubjectTr );
				tick.checked = true;
        	}	
        	if ( userSettingValues['CHANGE_MESSAGE_SUBJECT_WO_MARKER'] && fullMessage.indexOf('<i>') < 0 && fullMessage.indexOf('</i>') < 0 )	{        		
//        		div class="decision"	Kereskedelmi egyezmény elfogadása előtt és után..        		
        		var endOfFirstLine = fullMessage.indexOf('<br>');
        		var firstLine = endOfFirstLine > -1 ? fullMessage.substring(0, endOfFirstLine) : fullMessage;
        		var langBasedPrefix = circularMessage ? getOtherTextInLang('ALLIANCE_TYPE_MESSAGE') : getOtherTextInLang('PRIVATE_TYPE_MESSAGE');
        		langBasedPrefix = '[' + langBasedPrefix + ']';
        		var newSubject =  '<b>' + langBasedPrefix + '</b> - ';
        		newSubject += ( firstLine.length > 85 ) ? firstLine.substring(0, 85) + '...' : firstLine;
        		messageSubjectTd.innerHTML = newSubject;
        	}
		}     
        
    }
    
    if ( getMessageViewType() == 2 )	{
    	for (x = 0; x != c; x++) {
    		var currentMessageTr = messageTextDivs[trShifter*x + 1];
    		var messageSubjectTr = messageTextDivs[trShifter*x];
    		var deleteInput = $X("./td/input[starts-with(@name,'delete')]", messageSubjectTr );
    		var messageId = deleteInput.name.replace(/\D*[\[\]]/g, '');
    		messageSubjectTr.innerHTML = messageSubjectTr.innerHTML.replace( /mail\d{1,2}/g, 'mail_' + messageId );
    		messageSubjectTr.innerHTML = messageSubjectTr.innerHTML.replace( /button\d{1,2}/g, 'button_' + messageId );		
    		currentMessageTr.id = currentMessageTr.id.replace( /mail\d{1,2}/g, 'mail_' + messageId );
    	}
	}
    
}

function getPlayerName(senderTableData, debugVar){
    if (debugVar == 0) {
        debugVar++;
        var refElement = senderTableData.getElementsByTagName('a')[0];
        var senderName = refElement.innerHTML;
    }
}

function getMessageViewType(){
    /*
     1 = inbox
     2 = outbox
     3 = treaty
     4 = ally
     */
	if (messageViewType == null) {
		messageViewType = 1;
		if ( url.indexOf('diplomacyAdvisorOutBox') > 0 )	{
			messageViewType = 2;
		}
		else if ( url.indexOf('diplomacyAdvisorTreaty') > 0 )	{
			messageViewType = 3;
		}
		else if ( url.indexOf('diplomacyAdvisorAlly') > 0 )	{
			messageViewType = 4;
		}
	}
	
	return messageViewType;    
}

function appendMessageType2(subject, messageType)	{
	var firstPart = subject;
    if (subject.indexOf('-') > 0) {
        firstPart = subject.substring(0, subject.indexOf('-'));
    }
	return firstPart + '<b> = ' + messageType + ' </b>';
}

function isMessageForTradeGood(messageTypeIndex){
    return 1 == isMessageForTrade[messageTypeIndex];
}

// needed for icon display in message subjects
function checkIsAnyMessageTableOnScreen(){
    // after sending a reply, the url changes to s*.ikariam.*/index.php
    tableElements = document.getElementsByTagName('table');
    var i = 0;
    for (i = 0; i < tableElements.length; i++) {
        currTableElement = tableElements[i];
        if ('table01' == currTableElement.className && 'messages' == currTableElement.id) {
            return true; // I think, this condition met after sending a reply from the 'inbox'
        }
        if ('table01' == currTableElement.className && ('undefined' == currTableElement.id || '' == currTableElement.id)) {
            return true; // I think, this condition met after sending a second reply from the 'outbox'
        }
    }
    return false;
}

/*
 Functions to extend message list size
 */
function extendMessageList(){	
    existingMessageTableBody = $X("//*[@id='deleteMessages']/table/tbody");
	
	processMessageTable( existingMessageTableBody );
        
    var pagingLinkTd = $X("./tr/td[@class='paginator']", existingMessageTableBody);
	
	if ( pagingLinkTd == null || pagingLinkTd == 'undefined' )	{
		return;		
	}
		
	var aNodes = $x("./a", pagingLinkTd );
	var dataStr = aNodes[ aNodes.length - 1 ].href.toString().split('?')[1];	
			
	var startValue = parseInt( aNodes[ aNodes.length - 1 ].href.match( startValueRegexp ).toString().replace(/start=/, '') );

	var fromToRegexp = getMessageViewType() == 1 
		? new RegExp((startValue - 9 ) + ' - ' + startValue)
		: new RegExp((startValue - 10 ) + ' - ' + startValue);
		
	startValue -= 10;
	var endValue = startValue + userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'];
	var nrOfStartMessage = startValue;	
	
	var rows = $x("./tr[@class='text' or @class='entry' or @class='entry ' or @class='entry new']", existingMessageTableBody); // all message rows
	
	if ( rows.length != 30 && rows.length != 20 )	{
		replacePreviousPageLink(aNodes, startValue + 20, endValue + 20);
	}
	else	{
		switch (aNodes.length) {
			case 2:{
				replaceNextPageLink(aNodes, startValue, endValue, 0);
			}
			break;
			case 4:{
				replacePreviousPageLink(aNodes, startValue, endValue);
				replaceNextPageLink(aNodes, startValue, endValue, 2);
			}
			break;
		}
	}
	
	var textNodeStart = getMessageViewType() == 1 ? endValue - userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'] + 1 : endValue - userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'];
	var textNodeValue = textNodeStart + ' - ' + endValue;
	pagingLinkTd.innerHTML = pagingLinkTd.innerHTML.replace(fromToRegexp, textNodeValue);

	switch (rows.length) {
		case 30:{			
			var finalDataStr = '';
			for (var i = 1; i != pagesToLoad; ++i) {
				finalDataStr = dataStr.replace(startValueRegexp, 'start=' + (nrOfStartMessage += 10) );
				getMessagePages( finalDataStr, getMessagesForSequencedQuery);
			}			
		}
		break;
		
		case 20:	{			
			var finalDataStr = '';
			for (var i = 1; i != pagesToLoad; ++i) {
				finalDataStr = dataStr.replace(startValueRegexp, 'start=' + (nrOfStartMessage += 10));
				getMessagePages(finalDataStr, getMessagesForSequencedQuery);
			}
		}
		break;
		
	}
	if ( url.indexOf('view=diplomacyAdvisor') > 0 )	{
		saveUserSettingValue( 'PREV_DIPLOMACY_URL', url );
		dummyRequest(url.split('?')[0], url.split('?')[1]);		
	}
	else	{
		oldUrlStr = GM_getValue( 'PREV_DIPLOMACY_URL' );
		dummyRequest(oldUrlStr.split('?')[0], oldUrlStr.split('?')[1]);
	}
	
}

function getMessagesForSequencedQuery(page){
    if (page) {
//        var startDate = new Date();
//        GM_log('process start : ' + startDate.getMinutes() + ':' + startDate.getSeconds() + '.' + startDate.getMilliseconds());
        var insertMessages = $X(".//*[@id='deleteMessages']/table/tbody", createHiddenDiv('hidden_message_div_id', page));
		
		processMessageTable( insertMessages );
		
        var rows = $x("./tr[@class='text' or @class='entry' or @class='entry ' or @class='entry new']", insertMessages);
		
		if ( rows.length == 0 )	{
			return;
		}
		
		var aNodes = $x("./tr/td[@class='paginator']/a", insertMessages);		
		var dataStr = aNodes[ 1 ].href.toString().split('?')[1];			
		if (dataStr == aNodes[aNodes.length - 1].href.toString().split('?')[1] && rows.length == 30) {
			return;
		}
		
		var startValue =  parseInt(dataStr.match( startValueRegexp ).toString().replace(/start=/, '') ) + 10 ;
		var endValue = startValue + userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'];
		rows[0].appendChild( createInputElement('hidden', 'requeststart', startValue, null ) );
		
		// TODO - indexing is bad after generated "reply" event..
		
        if (existingMessageTableBody) {
			var insertAfter = null;
			var xPathStringForAppendedRequestStarts = "./tr[@class='entry' or @class='entry ' or @class='entry new']/input[@id='requeststart' and @value> " + startValue + " and @value< " + endValue + "]";			
			var nextNode = $X(xPathStringForAppendedRequestStarts, existingMessageTableBody);
			paginatorLink = $X("./tr/td[@class='paginator']", existingMessageTableBody);
			if (nextNode && nextNode != null && nextNode != undefined ) {
				insertAfter = nextNode.parentNode;
			}
			else {				
				insertAfter = paginatorLink.parentNode;
			}
			
			var outbox = getMessageViewType() == 2;
			
            for (var i = 0; i < rows.length; ++i) {
            	
            	if ( outbox )	{
            		
            	}
            	
                insertAfter = existingMessageTableBody.insertBefore(rows[i], insertAfter);
                if (insertAfter) {
                    insertAfter = insertAfter.nextSibling;
                }
            }
        }				
		
		if ( rows.length != 30 && rows.length != 20 )	{	
			var pageANodes = $x("./a", paginatorLink);			
			var cutEndNumberRegexp = new RegExp('- \\d{1,4}' );
			var endNumberValue = getMessageViewType() == 1
				? ( startValue + (rows.length / 3) )
				: ( startValue + (rows.length / 2) );
			paginatorLink.innerHTML = paginatorLink.innerHTML.replace(cutEndNumberRegexp, '- ' + endNumberValue );
			
			if (pageANodes.length == 2) {							
				if (pageANodes[0].firstChild.nodeName.toUpperCase() == 'IMG') {
				// system gave only next link.. but no next pages..
				// link pair generation based on the first query.. if the first has previous, then we get two pairs, so we can hide these links..					
//					GM_log('FIRST PAGE IS THE LAST');					
					paginatorLink.removeChild(paginatorLink.lastChild);
					paginatorLink.removeChild(paginatorLink.lastChild);
					paginatorLink.removeChild(paginatorLink.lastChild);
					paginatorLink.removeChild(paginatorLink.lastChild);
				}
				else if (pageANodes[1].firstChild.nodeName.toUpperCase() == 'IMG') {
					// system gave previous link.. 
					// this means, system says, the base query is the last page..
					GM_log( 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' );
					// I think, this will never happen
				}
			}
			else {
//				GM_log('LAST PAGE WITH NEXT LINK');
				paginatorLink.removeChild(paginatorLink.lastChild);
				paginatorLink.removeChild(paginatorLink.lastChild);
				paginatorLink.removeChild(paginatorLink.lastChild);
				paginatorLink.removeChild(paginatorLink.lastChild);
			}
			
		}
		
//        startDate = new Date();
//        GM_log('process end : ' + startDate.getMinutes() + ':' + startDate.getSeconds() + '.' + startDate.getMilliseconds());
    }
} 

function replacePreviousPageLink(aNodes, startValue, endValue){
	var aNodesIterator = 0;
	for ( aNodesIterator = 0; aNodesIterator != 2; aNodesIterator++ )	{
		aNodes[aNodesIterator].href = aNodes[aNodesIterator].href.replace(startValueRegexp, 'start=' + (startValue - userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE']) );		
		aNodes[aNodesIterator].title = aNodes[aNodesIterator].title.replace( /10/, userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'] );		
	}	
	aNodes[0].innerHTML = aNodes[0].innerHTML.replace(/10/, userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'] );
}

function replaceNextPageLink( aNodes, startValue, endValue, shiftValue)	{
	var aNodesIterator = 0;
	for ( aNodesIterator = shiftValue; aNodesIterator != aNodes.length; aNodesIterator++ )	{
		aNodes[aNodesIterator].href = aNodes[aNodesIterator].href.replace(startValueRegexp, 'start=' + endValue );
//		aNodes[aNodesIterator].title = aNodes[aNodesIterator].title.replace( /10/, userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'] );

//		aNodes[aNodesIterator].href = aNodes[aNodesIterator].href.replace(endValueRegexp, 'end=' + (endValue + userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE']) );

		aNodes[aNodesIterator].href = aNodes[aNodesIterator].href.replace(endValueRegexp, 'end=' + (endValue + 10) );
				
	}
	aNodes[aNodes.length - 1].innerHTML = aNodes[aNodes.length - 1].innerHTML.replace(/10/, userSettingValues['NUMBER_OF_MESSAGES_ON_PAGE'] );
}